<?php

namespace app\shop\model;

use app\admin\model\ShopModel;
use app\admin\model\ShopOrderModel;
use app\admin\model\ShopRefundOrderModel;
use app\crm\model\Coupon;
use app\crm\model\CouponProvideCustomer;
use app\crm\model\Customer;
use app\crm\model\CustomerAccount;
use app\crm\model\FollowRecord;
use app\admin\model\Common;
use app\crm\model\MedicalRecords;
use app\crm\model\ProductItem;
use app\crm\model\ShopPerson;
use app\crm\model\ShopGoods;
use app\crm\model\ShopOrderGoods;
use app\mini\model\AdminUser;
use think\facade\Db;
use think\model\concern\SoftDelete;
use app\common\traits\ActionRecordTrait;
use app\services\SendMsg;
use think\facade\Cache;

/**
 * 订单模型
 * @package app\shop\model
 * @author LIU
 * @create 2021-10-01
 */

class MedicalRecordsOrder extends Common
{
    use ActionRecordTrait;

    /**
     * 表名
     * @var string
     */

    protected $name = 'medical_records_order';

    protected $defaultSoftDelete = 0;

    /**
     * 获取sku信息
     * @return \think\model\relation\hasOne
     * @author SL
     * @create 2021-05-27 15:04
     */
    public function orderGoods()
    {
        return $this->hasOne(Goods::class,'id');
    }


    /**
     * 获取订单列表
     * @param  array $request 请求参数
     * @return array
     * @author SL
     * @create 2021-06-1
     */
    public function caseOrderList($request)
    {
        try
        {
            $userId  = $request['user_id'] ?? 0;
            $request = $this->fmtRequest($request);
            $where   = [];

            //病例id
             $case_id  = $request['map']['case_id'] ?? 0;
             if(!empty($case_id)){
                 $where[] = ['o.case_id', '=', $case_id];
             }

             $display_cannel = $request['map']['display_cannel']??0;

             if($display_cannel == 0){
                 $where[] = ['o.status', '<>', 4];
             }

            // 时间范围搜索
            if (!empty($request['map']['start_time']) || !empty($request['map']['end_time']))
            {
                if(!empty($request['map']['start_time']))
                {
                    $start_time = strtotime($request['map']['start_time'] . ' 00:00:00');
                }else
                {
                    $start_time = strtotime(date('Y-m-d 00:00:00'));
                }
                if(!empty($request['map']['end_time']))
                {
                    $end_time = strtotime($request['map']['end_time'] . ' 23:59:59');
                }else
                {
                    $end_time = strtotime(date('Y-m-d 23:59:59'));
                }
                // 添加时间范围条件
                $where[] = ['o.deal_time', 'between', [$start_time, $end_time]];
            }

            // 最低金额
            if(!empty($request['map']['low_total']))
            {
                $where[] = ['o.total_amount', '>=', $request['map']['low_total']];
            }

            // 最高金额
            if(!empty($request['map']['large_total']))
            {
                $where[] = ['o.total_amount', '<=', $request['map']['large_total']];
            }

            // 客户名称搜索
            if(!empty($request['map']['consignee']))
            {
                $where[] = ['c.customer_name', 'like', '%' . $request['map']['consignee'] . '%'];
            }

            // 店铺名称搜索
            if(!empty($request['map']['shop_name']))
            {
                $where[] = ['s.shop_name', 'like', '%' . $request['map']['shop_name'] . '%'];
            }
            // var_dump($where);die;
            // 使用 leftJoin 查询
            $sqlQuery = $this->alias('o')
                ->leftJoin('customer c', 'o.uid = c.id')
                ->leftJoin('shop s', 'o.shop_id = s.shop_id')
                ->leftJoin('shop_person sp', 'o.sale_id = sp.id')
                ->where($where);

            $dataCount = $sqlQuery->count();

            if ($dataCount) {
                $list = $sqlQuery->field('o.deal_time, o.uid, o.shop_id, o.order_type, o.status, o.total_amount, o.goods_price, o.sale_id, o.id, 
                        c.customer_name, c.king_no, c.nurse_id,
                        s.shop_name,
                        sp.name as sale_name')
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->order('o.id', 'desc')
                    ->select()->toArray();
                if ($list) {
                    $status = [
                        0=>'待支付',
                        1=>'已支付',
                        2=>'待拆单',
                        3=>'已下推',
                        4=>'已作废',
                    ];
                    $order_type = [
                        0=>'',
                        1=>'初诊',
                        2=>'复诊',
                        3=>'再消费',
                        4=>'诊疗',
                        5=>'其他',
                    ];

                    foreach($list as &$v){
                        $v['order_type'] = isset($order_type[$v['order_type']]) ? $order_type[$v['order_type']] : '';
                        $v['deal_time'] = date('Y-m-d', $v['deal_time']);
                        $v['status_text'] = isset($status[$v['status']]) ? $status[$v['status']] : '';
                        // 其他字段已经通过联表查询获取，无需额外处理
                    }
                }
            }

            $permission = get_user_permission_menu($userId, 'order_list_tag');
            $data = [];
            $data['menu_list'] = $permission ? $permission : [];
            $data['list'] = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;

            return $data;

        } catch (\Exception $e)
        {
            $this->error = $e->getMessage();
            return [];
        }

        // try {
        //     $userId  = $request['user_id'] ?? 0;
        //     $request = $this->fmtRequest($request);
        //     $where   = [];
        //     $case_id  = $request['map']['case_id'] ?? 0;
        //     if(!empty($case_id)){
        //         array_push($where, ['case_id', '=', $case_id]);
        //     }
        //     $display_cannel = $request['map']['display_cannel']??0;
        //     if($display_cannel == 0){
        //         array_push($where, ['status', '<>', 4]);
        //     }
        //     $start_time = $request['map']['start_time']??0;
        //     $end_time = $request['map']['end_time']??0;
        //     if(!empty($start_time) && !empty($end_time)){
        //         $start_time = strtotime($start_time);
        //         $end_time = strtotime($end_time);
        //         array_push($where, ['deal_time', 'between', "$start_time,$end_time"]);
        //     }

        //     $low_total = $request['map']['low_total']??0;
        //     if(!empty($low_total)){
        //         array_push($where, ['total_amount', '>=', $low_total]);
        //     }

        //     $large_total = $request['map']['large_total']??0;
        //     if(!empty($large_total)){
        //         array_push($where, ['total_amount', '<=', $large_total]);
        //     }
        //     $order_type = $request['map']['order_type']??0;
        //     if(!empty($order_type)){
        //         array_push($where, ['order_type', '=', $order_type]);
        //     }

        //     $sqlQuery = $this->where($where);
        //     $dataCount  = $sqlQuery->count();

        //     if ($dataCount) {

        //         $list = $sqlQuery->field('deal_time,uid,shop_id,order_type,status,total_amount,goods_price,sale_id,id')
        //             ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
        //             ->order('id','desc')
        //             ->select()->toArray();

        //         if ($list) {
        //             $status = [
        //                 0=>'待支付',
        //                 1=>'已支付',
        //                 2=>'待拆单',
        //                 3=>'已下推',
        //                 4=>'已作废',
        //             ];
        //             $order_type = [
        //                 0=>'',
        //                 1=>'初诊',
        //                 2=>'复诊',
        //                 3=>'再消费',
        //                 4=>'诊疗',
        //                 5=>'其他',
        //             ];
        //             $customer_ids = array_column($list,'uid');
        //             $customer = Customer::whereIn('id',$customer_ids)->column('king_no,customer_name,nurse_id','id');
        //             $shop_ids = array_column($list,'shop_id');
        //             $shop = ShopModel::whereIn('shop_id',$shop_ids)->column('shop_name','shop_id');
        //             $sale_ids = array_column($list,'sale_id');
        //             $sale = \app\crm\model\ShopPerson::whereIn('id',$sale_ids)->column('name','id');


        //             foreach($list as &$v){
        //                 $v['shop_name'] = isset($shop[$v['shop_id']])?$shop[$v['shop_id']]:'';
        //                 $v['sale_name'] = isset($sale[$v['sale_id']])?$sale[$v['sale_id']]:'';
        //                 $v['customer_name'] = isset($customer[$v['uid']])?$customer[$v['uid']]['customer_name']:'';
        //                 $v['king_no']    =  isset($customer[$v['uid']])?$customer[$v['uid']]['king_no']:'';
        //                 $v['order_type'] =  isset($order_type[$v['order_type']])?$order_type[$v['order_type']]:'';

        //                 $v['deal_time']  = date('Y-m-d', $v['deal_time']);
        //                 $v['status_text']  = isset($status[$v['status']])?$status[$v['status']]:'';
        //             }
        //         }
        //     }

        //     $permission = get_user_permission_menu($userId,'order_list_tag');
        //     $data              = [];
        //     $data['menu_list'] = $permission ? $permission : [];
        //     $data['list']      = $list ?? [];
        //     $data['dataCount'] = $dataCount ?? 0;

        //     return $data;

        // } catch (\Exception $e) {
        //     $this->error = $e->getMessage();
        //     return [];
        // }

    }




    /**
     * 创建订单-病例后开单
     * @param  array $request 请求参数
     * @return bool
     * @author SL
     * @create 2021-06-03
     */
    public function caseCreateOrder($request)
    {
        try {
            $validate = new \app\shop\validate\Order();
            if (!$validate->scene('create')->check($request)) {

                $this->error = $validate->getError();
                return false;
            }
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }

        Db::startTrans();
        try {

            $time = time();
            $orderGoodsListArr = $request['goodsList'];
            $case_id = $request['case_id']??0;
            if(empty($case_id)){
                throw new \Exception('病例id不合法');
            }
            if(!empty(Cache::get($case_id.'value'))){
                throw new \Exception("目前操作频繁，请稍后重试.");
            }
            Cache::set($case_id.'value',1,10);


            $case = MedicalRecords::find($case_id);
            $case_create_day_times = strtotime(date('Y-m-d',$case->treatment_date));
            $day_times = strtotime(date('Y-m-d'));
//            if($case_create_day_times != $day_times){
//                throw new \Exception('不是当天病例，无法创建订单');
//            }

            $refund_type_plus = $request['refund_type_plus']??0;
            if(!in_array($refund_type_plus,[1,2,3,4,5]) ){
                throw new \Exception('请选择支付方式');
            }

            $customer_id = trim($request['uid']);
            $customer_data = Customer::with(['info'=>function($query)use($customer_id){
                $query->field('id,type_store');
            }])->where('id',$customer_id)
                ->field('source_id,source_type_id,shop_id,telephone,id')
                ->find()->toArray();
            if($customer_data['info']['type_store'] == 4){
                throw new \Exception('订单无法创建.');
            }


            $refundModel = new Refund();
            list($benj,$zengj,$customerMoney) = $refundModel->customerBalanceVerify($customer_id);


            $deduct_balance = $request['deduct_balance']??0; //使用组合支付 输入需要扣款的本金
            $deduct_gift = $request['deduct_gift']??0;       //使用组合支付 输入需要扣款赠金
            $pay_mode = $request['pay_mode']??0;             //组合支付-第二种支付方式

            if(in_array($refund_type_plus,[4,5])){
                //余额支付和组合支付
                if($refund_type_plus ==5 && !in_array($pay_mode,[1,2,3])){
                    throw new \Exception('请选择第二种支付方式');
                } else if($refund_type_plus ==5 && $deduct_balance > $benj &&  $deduct_gift > $zengj ){
                    throw new \Exception('顾客剩余，不足扣款');
                }elseif($refund_type_plus ==4 &&  $benj<0 && $zengj<0 ){
                    throw new \Exception('顾客剩余，不足扣款.');
                }
            }


            //获取门店商品信息
            $shop = ShopModel::where('shop_id',$request['shop_id'])->lock(true)->field('shop_id,type,keycode,shop_name,market_name,market_id')->find();

            // 支付总金额 /  产品的总金额 / 项目总金额，排除优惠券
            $payAmount = $productAmount = $projectAmount =   [];
            $goods_price = [];
            $is_have_cjyh = $is_have_goods =   [];
            $cjyh = 0; //自己选择冲减优惠
            $project_arr = $project_ids = $product_project_arr = $product_ids =
            $cjyh_arr = [];
            $kcbj = $kczj = $cjyh_bj =  $cjyh_zj = [];
            $zero_goods_arr = []; // 0元单商品（商品+品项）
            foreach ($orderGoodsListArr as $key => $val) {
                if(!isset($val['number']) || empty($val['number'])  ) {
                    throw new \Exception("请填写销售数量");
                }

                //0元（品项+商品）
                if($val['pay_price'] == 0 && $val['id'] != 170){
                    array_push($zero_goods_arr,$val);
                    if($val['goods_type'] == 1){
                        array_push($project_ids,$val['id']);
                    }elseif($val['goods_type'] == 2) {
                        array_push($product_ids,$val['id']);
                    }
                }

                if(in_array($val['goods_type'],[1,2]) && $val['pay_price'] <0 ){
                    throw new \Exception('价格有误');
                }

                if($val['goods_type'] == 2 && $val['pay_price'] >0 && $val['id'] != 170 ) {
                    //关于商品-判断 不包含冲减优惠
                    if(!in_array($val['business_type'],[1,2,3,4])){
                        throw new \Exception('请选择项目分类');
                    }
                    array_push($is_have_goods,1);
                    array_push($product_project_arr,$val);
                    array_push($product_ids,$val['id']);
                    $productAmount[] = bcmul($val['pay_price'], $val['number'], 2);

                } elseif ($val['goods_type'] == 1 && $val['pay_price'] >0){
                    //关于品项-判断
                    $projectAmount[] = bcmul($val['pay_price'], $val['number'], 2);
                    array_push($is_have_goods,1);
                    array_push($product_project_arr,$val);
                    array_push($project_ids,$val['id']);
                }
                //冲减优惠-判断
                if($val['id'] == 170) {
                    array_push($product_ids,170);
                    if ($val['pay_price'] < 0) {
                        throw new \Exception('冲减优惠不能为0');
                    }
                    $cjyh = bcmul($val['pay_price'], $val['number'], 2);
                    array_push($is_have_cjyh, 1);
                    array_push($cjyh_arr, $val);
                }

            }


            $is_have_cjyh_count = count($is_have_cjyh);
            if($is_have_cjyh_count >1){
                throw new \Exception('同一个单子不能出现两项冲减优惠');
            }else if ($is_have_cjyh_count >0 && empty($is_have_goods) ){
                throw new \Exception('冲减优惠没有优惠商品');
            } else if($is_have_cjyh_count >0 && $cjyh == 0){
                throw new \Exception('冲减优惠不能等于零');
            }


            $goods_price = bcadd(array_sum($goods_price),0,2); //商品的价格
            $productAmount = bcadd(0,array_sum($productAmount),2); //商品之和
            $projectAmount = bcadd(0,array_sum($projectAmount),2); //项目之和

            $total_amount = $productProjectAmount = bcadd($productAmount,$projectAmount,2); //优惠前的订单金额
            $after_order_amount = bcadd($total_amount,$cjyh,2);
            $is_order_zero = 0; //订单价格是否为0元  1 是  0否
            if($after_order_amount == 0){
                $is_order_zero = 1;
            }
            if($is_have_cjyh_count >0 && $total_amount < $cjyh){
                throw new \Exception('冲减优惠无法使用');
            }

            $operator_name = $request['operator_name'];   //操作人姓名
            $operator_id   = $request['operator_id'];     //操作人id

            // 验证
            $data = [
                'case_id' => $case_id,
                'refund_type_plus' => $refund_type_plus,
                'deduct_balance' => $deduct_balance,
                'deduct_gift'    => $deduct_gift,
                'pay_mode'       => $pay_mode,
                'pay_balance'    => 0,

                'uid'                =>  $customer_id, // 客户
                'source_type_id'     =>  $customer_data['source_type_id'],
                'source_id'          =>  $customer_data['source_id'],
                'consignee'          => trim($request['consignee']), // 收货人
                'order_no'           => $this->getOrderNo(), // 订单号
                'sale_id'            => $request['sale_id'], // 销售员id
                'sale_name'          => trim($request['sale_name']), // 销售员姓名
                'shop_id'            => $customer_data['shop_id'], // 门店id
                'shop_name'          => trim($shop['shop_name']), // 门店名称
                'operator_id'        => $operator_id,//制单员id
                'operator_name'      => $operator_name,//制单员姓名
                'create_time'        => $time, // 创建时间
                'deal_time'          => time(), // 成交日期
                'goods_price'        => $goods_price, // 订单标准金额 之和
                'total_amount'       => $total_amount, // 订单总金额 之和

                'order_amount'       =>  0, // 订单优惠后的金额
                'pay_amount'         =>  0, // 实收本金
                'gift_amount'        =>  0, // 实收赠金

                'description'           => isset($request['description']) ? $request['description'] : '', // 订单描述
                'order_type'            => $customer_data['info']['type_store'], // 订单类型 1新单 2补单
                'sales_policy'          => isset($request['sales_policy'])? $request['sales_policy'] : '', // 销售政策编码
                'market_id'             => $shop['market_id'] , // 市场id
                'market_name'           => $shop['market_name'], // 市场名称
                'sales_organization'    => isset($request['sales_organization']) ? $request['sales_organization'] : 0, // 销售组织编码
                'sales_name'           => isset($request['sales_name']) ? $request['sales_name'] : '', // 销售组织名称
                'settlement_organization' => isset($request['settlement_organization']) ? $request['settlement_organization'] : 0, // 结算组织编码
                'settlement_name'       => isset($request['settlement_name']) ? $request['settlement_name'] : '', // 结算组织名称
                'delivery_name'         => isset($request['delivery_name']) ? $request['delivery_name'] : '', // 发货部门名称
                'delivery_king'         => isset($request['delivery_king']) ? $request['delivery_king'] : '', // 发货部门编码
            ];
            $order = $this->create($data);

            if ($order) {
                $customerModel = new \app\crm\model\Customer();
                //商品-除冲减优惠和0元单
                $shopGoods = [];
                if(!empty($product_ids)){
                    $shopGoods = ShopGoods::whereIn('id', $product_ids)
                        ->where('status', 1)
                        ->column('name,category_id,kingdee_code,goods_price,spec_name,unit_code,unit_name,is_prestock', 'id');
                }
                //品项-除冲减优惠和0元单
                $project = [];
                if(!empty($project_ids)){
                    $project = ProductItem::whereIn('id',$project_ids)
                        ->where('status',1)
                        ->column('unit_code,unit_name,kingdee_code,price,name,number,product_info,type_one,type_two,type_three','id');
                }
                $MedicalRecordsOrderGoodsModel = new MedicalRecordsOrderGoods();

                $discount_amount_arr = [];//冲减优惠-商品优惠后的总金额
                //商品判断-goods_type = 2 -商品  goods_type = 1  品项
                $product_project_arr_count = count($product_project_arr);

                foreach ($product_project_arr as $pk => &$pv) {
                    if ($pv['pay_price'] > 0 && $pv['prestock_type'] != 3 ) {
                        $customerBalance['money'] = $benj;
                        $customerBalance['complimentary_money'] = $zengj;

                        $one_product_amount = bcmul($pv['pay_price'], $pv['number'], 2);

                        $discount_amount = 0; //优惠金额
                        if($is_order_zero == 1){
                            $discount_amount = bcsub(0,$one_product_amount,2);
                            $one_product_amount = 0;
                        }else{
                            if ($productProjectAmount > 0 && $cjyh != 0) {
                                //涉及到冲减优惠
                                if ($product_project_arr_count > 1) {
                                    if ($pk + 1 == $product_project_arr_count) {
                                        $discount_amount = bcsub($cjyh, bcadd(0, array_sum($discount_amount_arr), 2), 2); //最后一个优惠金额
                                    } else {
                                        $discount_amount = bcmul($cjyh, ($one_product_amount/$productProjectAmount), 2); //优惠金额
                                    }
                                } else {
                                    $discount_amount = bcmul($cjyh, ($one_product_amount/$productProjectAmount), 2); //优惠金额
                                }
                                $one_product_amount = bcadd($one_product_amount, $discount_amount, 2);//优惠后的价格
                            }
                        }

                        array_push($discount_amount_arr,$discount_amount);

                        $customerBalance['actual_order_amout'] = $one_product_amount; //优惠后的价格
                        $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单明细消耗的本金、赠金、店转
                        $bj = bcadd($pay_money['pay_benjin_amount'], 0, 2);  //单条优惠后的本金
                        $zj = bcadd($pay_money['pay_zengjin_amount'], 0, 2); //单条优惠后的赠金

                        array_push($kcbj, $bj);
                        array_push($kczj, $zj);

                        $customerBalance['actual_order_amout'] = $discount_amount;
                        $cjyh_pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单明细优惠的本金、赠金、店转
                        $pv['discount_amount'] = $discount_amount;    //折扣金额
                        $cjyhbj = bcadd($cjyh_pay_money['pay_benjin_amount'], 0, 2);  //单条优惠后的本金
                        $cjyhzj = bcadd($cjyh_pay_money['pay_zengjin_amount'], 0, 2); //单条优惠后的赠金
                        array_push($cjyh_bj, $cjyhbj);
                        array_push($cjyh_zj, $cjyhzj);

                        $pv['after_discount_amount'] = $one_product_amount;    //优惠后金额

                    }

                    $orderGoodsList = [];
                    $orderGoodsList['pay_amount'] = $bj;
                    $orderGoodsList['gift_amount'] = $zj;
                    $orderGoodsList['order_id'] = $order->id;
                    $orderGoodsList['create_time'] = $time;
                    $orderGoodsList['goods_id'] = $pv['id'];

                    if($pv['goods_type'] == 1){
                        $orderGoodsList['goods_name'] = $pv['name'];
                        $orderGoodsList['kingdee_code'] = isset($project[$pv['id']])?$project[$pv['id']]['kingdee_code']:'';
                        $orderGoodsList['goods_price']  =  $pv['goods_price'];
                        $orderGoodsList['pay_price']    = $pv['pay_price'];
                        $orderGoodsList['spec_name'] = $pv['spec_name'];

                        $orderGoodsList['unit_code'] = isset($project[$pv['id']])?$project[$pv['id']]['unit_code']:'';
                        $orderGoodsList['unit_name'] =  isset($project[$pv['id']])?$project[$pv['id']]['unit_name']:'';

                        $orderGoodsList['number'] = $pv['number'];
                        $orderGoodsList['desc'] = $pv['desc'];
                        $orderGoodsList['is_project'] = 1;//是否服务 1 是 2否
                        $orderGoodsList['category_id'] =  $jv['category_id']??0;
                        $orderGoodsList['service_goods_str'] = isset($project[$pv['id']])?$project[$pv['id']]['product_info']:'';
                        $orderGoodsList['is_coupon_goods'] =  0;;//是否优惠券商品 0否 1是
                        $orderGoodsList['project_type'] =  1;//服务类型 1 按次 2按天
                        $orderGoodsList['service_number'] = isset($project[$pv['id']])?$project[$pv['id']]['number']:0;//服务次数
                    }else if($pv['goods_type'] == 2){
                        $orderGoodsList['goods_name'] = $shopGoods[$pv['id']]['name'];
                        $orderGoodsList['kingdee_code'] = $shopGoods[$pv['id']]['kingdee_code'];
                        $orderGoodsList['goods_price'] = $shopGoods[$pv['id']]['goods_price'];
                        $orderGoodsList['pay_price'] = $pv['pay_price'];
                        $orderGoodsList['spec_name'] = $shopGoods[$pv['id']]['spec_name'];
                        $orderGoodsList['unit_code'] = $shopGoods[$pv['id']]['unit_code'];
                        $orderGoodsList['unit_name'] = $shopGoods[$pv['id']]['unit_name'];
                        $orderGoodsList['number'] = $pv['number'];
                        $orderGoodsList['desc'] = $pv['desc'];
                        $orderGoodsList['is_project'] = 2;//是否服务 1 是 2否
                        $orderGoodsList['category_id'] = $shopGoods[$pv['id']]['category_id'];
                    }


                    $orderGoodsList['is_gift'] = isset($pv['is_gift']) ? $pv['is_gift'] : 0;  //是否为赠品
                    $orderGoodsList['house_code'] = $pv['house_code'];

                    $orderGoodsList['coupon_type'] = isset($pv['coupon_type']) ? $pv['coupon_type'] : 0;//优惠券类型
                    $orderGoodsList['house_code_name'] = isset($pv['house_code_name']) ? $pv['house_code_name'] : '';
                    $orderGoodsList['goods_alias_name'] = isset($pv['goods_alias_name']) ? $pv['goods_alias_name'] : '';
                    $orderGoodsList['prestock_type'] = isset($pv['prestock_type']) ? $pv['prestock_type'] : 0; //预存货类型
                    $orderGoodsList['takeout_stock_num'] = isset($pv['out_num']) ? $pv['out_num'] : 0;  //出货数量
                    $orderGoodsList['data_business_type'] = isset($pv['business_type']) ? $pv['business_type'] : 0;  //业务类型
                    $orderGoodsList['data_business_two_type'] = isset($pv['business_two_type']) ? $pv['business_two_type'] : 0;
                    $orderGoodsList['discount_amount'] = isset($pv['discount_amount']) ? $pv['discount_amount'] : 0;  ////折扣金额
                    $orderGoodsList['after_discount_amount'] = isset($pv['after_discount_amount']) ? $pv['after_discount_amount'] : 0;  //优惠后金额
                    $order_goods_res = $MedicalRecordsOrderGoodsModel->create($orderGoodsList);
                }

                //冲减优惠入库
                foreach ($cjyh_arr as $ck => &$cv) {
                    $orderGoodsList = [];
                    $orderGoodsList['pay_amount'] = bcadd(0,array_sum($cjyh_bj),2);
                    $orderGoodsList['gift_amount'] =  bcadd(0,array_sum($cjyh_zj),2);
                    $orderGoodsList['shop_transfer_amount'] = 0;
                    $orderGoodsList['order_id'] = $order->id;
                    $orderGoodsList['create_time'] = $time;
                    $orderGoodsList['goods_id'] = $cv['id'];
                    $orderGoodsList['goods_name'] = $shopGoods[$cv['id']]['name'];
                    $orderGoodsList['kingdee_code'] = $shopGoods[$cv['id']]['kingdee_code'];
                    $orderGoodsList['goods_price'] = $shopGoods[$cv['id']]['goods_price'];
                    $orderGoodsList['pay_price'] = $cv['pay_price'];
                    $orderGoodsList['spec_name'] = $shopGoods[$cv['id']]['spec_name'];
                    $orderGoodsList['unit_code'] = $shopGoods[$cv['id']]['unit_code'];
                    $orderGoodsList['unit_name'] = $shopGoods[$cv['id']]['unit_name'];
                    $orderGoodsList['number'] = $cv['number'];
                    $orderGoodsList['desc'] = $cv['desc'];
                    $orderGoodsList['is_project'] = 2;//是否服务 1 是 2否
                    $orderGoodsList['category_id'] = $shopGoods[$cv['id']]['category_id'];

                    $orderGoodsList['is_gift'] = isset($cv['is_gift']) ? $cv['is_gift'] : 0;  //是否为赠品
                    $orderGoodsList['house_code'] = $cv['house_code'];
                    $orderGoodsList['coupon_type'] = isset($cv['coupon_type']) ? $cv['coupon_type'] : 0;//优惠券类型
                    $orderGoodsList['house_code_name'] = isset($cv['house_code_name']) ? $cv['house_code_name'] : '';
                    $orderGoodsList['goods_alias_name'] = isset($cv['goods_alias_name']) ? $cv['goods_alias_name'] : '';
                    $orderGoodsList['prestock_type'] = isset($cv['prestock_type']) ? $cv['prestock_type'] : 0; //预存货类型
                    $orderGoodsList['takeout_stock_num'] = isset($cv['out_num']) ? $cv['out_num'] : 0;  //出货数量
                    $orderGoodsList['data_business_type'] = isset($cv['business_type']) ? $cv['business_type'] : 0;  //业务类型
                    $orderGoodsList['data_business_two_type'] = isset($cv['business_two_type']) ? $cv['business_two_type'] : 0;  //业务类型
                    $orderGoodsList['after_discount_amount'] =  bcmul($cv['pay_price'],$cv['number'],2);
                    $order_goods_res = $MedicalRecordsOrderGoodsModel->create($orderGoodsList);
                }

                //0元单 商品+品相
                foreach ($zero_goods_arr as $zk => &$zv) {
                    $orderGoodsList = [];
                    $orderGoodsList['pay_amount'] =0;
                    $orderGoodsList['gift_amount'] =  0;
                    $orderGoodsList['shop_transfer_amount'] = 0;
                    $orderGoodsList['order_id'] = $order->id;
                    $orderGoodsList['create_time'] = $time;
                    $orderGoodsList['goods_id'] = $zv['id'];
                    $orderGoodsList['is_project'] = $zv['goods_type'];//是否服务 1 是 2否
                    if($zv['goods_type'] ==1){
                        //品项
                        $orderGoodsList['goods_name'] = $project[$zv['id']]['name']??'';
                        $orderGoodsList['kingdee_code'] = $project[$zv['id']]['kingdee_code']??'';
                        $orderGoodsList['goods_price'] = $project[$zv['id']]['goods_price']??'';
                        $orderGoodsList['pay_price'] = $zv['pay_price'];
                        $orderGoodsList['spec_name'] = $project[$zv['id']]['spec_name']??'';
                        $orderGoodsList['unit_code'] = $project[$zv['id']]['unit_code']??'';
                        $orderGoodsList['unit_name'] = $project[$zv['id']]['unit_name']??'';
                        $orderGoodsList['category_id'] = 0;
                        $orderGoodsList['service_number'] = $project[$zv['id']]['number']??0;//服务次数
                        $orderGoodsList['service_goods_str'] = isset($project[$zv['id']])?$project[$zv['id']]['product_info']:'';
                    }else{
                        //商品
                        $orderGoodsList['goods_name'] = $shopGoods[$zv['id']]['name']??'';
                        $orderGoodsList['kingdee_code'] = $shopGoods[$zv['id']]['kingdee_code']??'';
                        $orderGoodsList['goods_price'] = $shopGoods[$zv['id']]['goods_price']??'';
                        $orderGoodsList['pay_price'] = $zv['pay_price'];
                        $orderGoodsList['spec_name'] = $shopGoods[$zv['id']]['spec_name']??'';
                        $orderGoodsList['unit_code'] = $shopGoods[$zv['id']]['unit_code']??'';
                        $orderGoodsList['unit_name'] = $shopGoods[$zv['id']]['unit_name']??'';
                        $orderGoodsList['category_id'] = $shopGoods[$zv['id']]['category_id']??'';
                        $orderGoodsList['service_number'] =  0;//服务次数
                    }

                    $orderGoodsList['number'] = $zv['number'];
                    $orderGoodsList['desc'] = $zv['desc'];
                    $orderGoodsList['is_coupon_goods'] = 0;//是否优惠券商品 0否 1是
                    $orderGoodsList['start_time'] = 0; //服务开始时间
                    $orderGoodsList['end_time'] = 0;  //服务结束时间
                    $orderGoodsList['is_gift'] = isset($zv['is_gift']) ? $zv['is_gift'] : 0;  //是否为赠品
                    $orderGoodsList['house_code'] = $zv['house_code'];
                    $orderGoodsList['coupon_type'] = isset($zv['coupon_type']) ? $zv['coupon_type'] : 0;//优惠券类型
                    $orderGoodsList['house_code_name'] = isset($zv['house_code_name']) ? $zv['house_code_name'] : '';
                    $orderGoodsList['goods_alias_name'] = isset($cv['goods_alias_name']) ? $zv['goods_alias_name'] : '';
                    $orderGoodsList['prestock_type'] = isset($zv['prestock_type']) ? $zv['prestock_type'] : 0; //预存货类型
                    $orderGoodsList['takeout_stock_num'] = isset($zv['out_num']) ? $zv['out_num'] : 0;  //出货数量
                    $orderGoodsList['data_business_type'] = isset($zv['business_type']) ? $zv['business_type'] : 0;  //业务类型
                    $orderGoodsList['data_business_two_type'] = isset($zv['business_two_type']) ? $zv['business_two_type'] : 0;  //业务类型
                    $orderGoodsList['after_discount_amount'] = 0;
                    $order_goods_res = $MedicalRecordsOrderGoodsModel->create($orderGoodsList);
                }

                //推云星空使用
                $shop_order_update= [
                    'pay_amount'     => bcadd(array_sum($kcbj),0,2), // 实收本金
                    'gift_amount'    => bcadd(array_sum($kczj),0,2), // 实收赠金
                    'order_amount'   => bcadd(bcadd(array_sum($kcbj),0,2),bcadd(array_sum($kczj),0,2),2),
                ];


                if($refund_type_plus ==5 && $deduct_balance > $benj &&  $deduct_gift > $zengj ){
                    throw new \Exception('顾客剩余，不足扣款.');
                }

                $shop_order_update ['total_amount'] = bcadd($shop_order_update['pay_amount'],$shop_order_update['gift_amount'],2);
                if($request['refund_type_plus'] == 4 || $request['refund_type_plus'] == 2 ){
                    $shop_order_update['status'] =2;
                }

                //创建待支付订单-收款单
                if($refund_type_plus == 1|| $refund_type_plus == 3 || ($refund_type_plus == 5 && in_array($pay_mode,[1,3]))){

                    if(in_array($refund_type_plus,[1,3])){
                        $shop_order_update['deduct_balance'] = $shop_order_update ['total_amount'];//实际扣款本金
                        $api_type = 5;
                        $pay_amount =  $shop_order_update ['total_amount'];  //通联远程和通联支付 都是订单的总金额
                        $gift_amount = 0;
                    }elseif ($refund_type_plus == 5 && in_array($pay_mode,[1,3])){
                        //第二种组合方式
                        $api_type = 6;
                        $pay_amount =  bcsub($shop_order_update['total_amount'],bcadd($data['deduct_balance'],$data['deduct_gift'],2),2);  //订单总额-输入的本金+赠金
                        $gift_amount = 0;
                        $shop_order_update['pay_balance'] =$pay_amount; //组合支付 金额
                    }

                    if($pay_amount >0){
                        $orderData = [
                            'uid'                => trim($data['uid']), // 客户
                            'uid_source_type_id' => $data['source_type_id']??0,
                            'source_id'          => $data['source_id']??0,
                            'consignee'          => trim($data['consignee']), // 收货人
                            'refund_order_no'    => time().rand(1000,9999), // 订单编号, // 订单号
                            'sale_id'            => $data['sale_id'], // 销售员id
                            'sale_name'          => trim($request['sale_name']), // 销售员姓名
                            'shop_id'            => $data['shop_id'], // 门店id
                            'shop_name'          => trim($data['shop_name']), // 门店名称
                            'shop_type'          => $shop['shop_type'], // 门店属性
                            'market_id'          => $shop['market_id'], // 市场id
                            'market_name'        => $shop['market_name'], // 市场名称

                            'operator_id'        => $data['operator_id'],//制单员id
                            'operator_name'      => $operator_name,//制单员姓名
                            'create_time'        => $time, // 创建时间
                            'deal_time'          => $data['deal_time'], // 成交日期
                            'total_amount'       => $pay_amount, // 应退（收）金额
                            'pay_amount'         =>  $pay_amount , // 实退（收）本金
                            'gift_amount'        =>  $gift_amount, // 实退（收）赠金

                            'description'          => isset($data['description']) ? $data['description'] : '', // 订单描述

                            'order_type'           => $data['order_type'], // 订单类型 1新单 2补单

                            'sales_policy'         =>  '', // 销售政策编码
                            'refund_type'          =>  '101.02', // 退款类型 101.01 店转  101.02 退款

                            'type'                 => 3,//退款单类型 1退款单 2退货单

                            'sales_organization'       => isset($data['sales_organization']) ? $data['sales_organization'] : 0, // 销售组织编码
                            'sales_name'                =>    $data['sales_name'], // 销售组织名称

                            'settlement_organization' => $data['settlement_organization'], // 结算组织编码
                            'settlement_name'         => $data['settlement_name'], // 结算组织名称

                            'refund_type_plus' => $data['refund_type_plus'] , // 收款方式  通联支付  传统支付  通联远程
                            'shanghu_type'     => 1, // 商户分类1是公户，2是私户
                            'is_pay'           => 0, // 是否支付：0未支付，1已支付
                            'api_type'         =>  5, //0中台系统 1商城积分兑换订单 2商城普通订单
                            'api_order_id'     => 0, //商城订单ID
                            'case_id'=>$case_id,
                            'case_order_id'=>$order->id
                        ];
                        $shopRefundOrderModel =new ShopRefundOrderModel();
                        // 需要放开
                        $shopRefundOrderRes = $shopRefundOrderModel->create($orderData);

                        $orderGoodsList['order_id'] = $shopRefundOrderRes->id;
                        $orderGoodsList['create_time'] = $time;
                        $orderGoodsList['refund_mode'] = '02';
                        $orderGoodsList['refund_mode_name'] = '刷卡/微信/支付宝';
                        $orderGoodsList['bank_number'] = '';
                        $orderGoodsList['data_business_type'] = 0;
                        $orderGoodsList['data_business_two_type'] = 0;
                        $orderGoodsList['data_sales_policy'] = "";  //销售政策编码
                        $orderGoodsList['pay_price'] = $pay_amount;
                        $orderGoodsList['gift_price'] = $gift_amount;
                        $orderGoodsList['descs'] = '病例开单收款';

                        $shopRefundOrderGoodsModel = new ShopRefundOrderGoods();
                        $res =  $shopRefundOrderGoodsModel->save($orderGoodsList);
                    }

                }

                $res = MedicalRecordsOrder::where('id',$order->id)->update($shop_order_update);
                Db::commit();

                //如果成交日期不是今天 修改保有代码
                if(!empty($request['deal_time']) && $request['deal_time'] != '0000-00-00' && $request['deal_time'] !== date('Y-m-d'))
                {
                    $logData = ['shop_id' => $request['shop_id'],'date' => $request['deal_time'],'create_time' => date('Y-m-d')];
                    Db::name('shop_retention_log')->insert($logData);
                }


                $this->error = '创建成功';

                return true;

            }else{
                throw new \Exception("病例开单创建失败，请稍后再试");
            }

        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }


    /**
     * 病例开单-订单取消
     * @param  array $request 请求参数
     * @return bool
     * @author SL
     * @create 2021-06-03
     */
    public function caseOrderCancel($request)
    {
        Db::startTrans();
        try {
            $order_id = $request['order_id'] ??0;
            if(empty($order_id)){
                throw new \Exception('订单id不合法');
            }
            $order = $this->find($order_id);
            //如果已经拆开订单了，就无法作废了
            if($order->status==3){
                throw new \Exception('有订单产生，订单无法作废');
            }

            $order->status = 4;
            $order->cancel_time = time();

            $res = $order->save();
            if($res){
                Db::commit();
                return ['msg'=>"取消成功"];
            }else{
                throw new \Exception('订单作废失败，请稍后重试');
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return [];
        }
    }


    /**
     * 病例开单-订单编辑
     * @param  array $request 请求参数
     * @return bool
     * @author SL
     * @create 2021-06-03
     */
    public function caseUpdateOrder($request)
    {
        Db::startTrans();
        try {
            $order_id = $request['id'] ??0;
            if(empty($order_id)){
                throw new \Exception('订单id不合法');
            }
            if(!empty(Cache::get($order_id.'value'))){
                throw new \Exception("目前操作频繁，请稍后重试");
            }
            Cache::set($order_id.'value',1,10);
            $goods = $request['goodsList']??[];
            $project_ids =[];
            $medicalRecordsOrderGoodsModel = new MedicalRecordsOrderGoods();
            $is_send_yxk = [];//是否推送云星空
            foreach ($goods as $k=>$v){

                if($v['is_project'] ==1){
                    array_push($is_send_yxk,0);
                }elseif($v['is_project'] == 2 && $v['kingdee_code'] != '101.12.098' ){
                    array_push($is_send_yxk,1);
                }

                if($v['is_project']==1){
                    array_push($project_ids,$v['goods_id']);
                }
                $goodsInfo = $medicalRecordsOrderGoodsModel->where('id',$v['id'])->find();
                $goodsInfo->goods_alias_name = $v['goods_alias_name'];
                $goodsInfo->save();
            }
            $order = $this->lock(true)->find($order_id);

            if($order['status'] == 4){
                throw new \Exception('订单已经作废，无法修改');
            }

            $refund = new Refund();
            list($benj,$zengj,$customerMoney) = $refund->customerBalanceVerify($order->uid);

//            $order->order_type = $request['order_type'];
            //确认拆单条件：确认拆单+传统支付 + 余额支付

            $customerModel = new \app\crm\model\Customer();

            $shop = ShopModel::where('shop_id',$order['shop_id'])->field('shop_name,market_name,shop_type,market_id')->find(); //门店信息

            $sale = ShopPerson::where('id',$order['sale_id'])->field('name')->find();  //开单人信息

            $operator = AdminUser::where('id',$order['operator_id'])->field('realname')->find();   //操作人信息

            $is_send_yxk_receipt = false;  //收款单推星空使用
            $receipt_id = 0;  //收款单推星空使用
            if($request['is_affirm'] ==1 && $order->refund_type_plus == 2 )
            {

                $time = time();
                //收款单
                $orderData = [
                    'uid'                => trim($order['uid']), // 客户
                    'uid_source_type_id' => $order['source_type_id']??0,
                    'source_id'          => $order['source_id']??0,
                    'consignee'          => trim($order['consignee']), // 收货人
                    'refund_order_no'    => time().rand(1000,9999), // 订单编号, // 订单号

                    'sale_id'            => $order['sale_id'], // 销售员id
                    'sale_name'          => trim($sale['name']), // 销售员姓名

                    'shop_id'            => $order['shop_id'], // 门店id
                    'shop_name'          => trim($shop['shop_name']), // 门店名称
                    'shop_type'          => $shop['shop_type'], // 门店属性
                    'market_id'          => $shop['market_id'], // 市场id
                    'market_name'        => $shop['market_name'], // 市场名称

                    'operator_id'        => $order['operator_id'],//制单员id
                    'operator_name'      => $operator['realname'],//制单员姓名
                    'create_time'        => $time, // 创建时间
                    'deal_time'          => $order['deal_time'], // 成交日期
                    'total_amount'       => $order->total_amount , // 应退（收）金额
                    'pay_amount'         => $order->total_amount , // 实退（收）本金
                    'gift_amount'        =>  0, // 实退（收）赠金
                    'description'          => '病例开单-支付方式：传统支付', // 订单描述
                    'order_type'           => $order['order_type'], // 订单类型 1新单 2补单
                    'sales_policy'         =>  '', // 销售政策编码
                    'refund_type'          =>  '101.02', // 退款类型 101.01 店转  101.02 退款
                    'type'                 => 3,//退款单类型 1退款单 2退货单

                    'sales_organization'       =>  $order['sales_organization'] , // 销售组织编码
                    'sales_name'                => $order['sales_name'], // 销售组织名称

                    'settlement_organization' => $order['settlement_organization'], // 结算组织编码
                    'settlement_name'         => $order['settlement_name'], // 结算组织名称

                    'refund_type_plus' => 2 , // 收款方式  通联支付  传统支付  通联远程
                    'shanghu_type'     => 1, // 商户分类1是公户，2是私户
                    'is_pay'           => 1, // 是否支付：0未支付，1已支付
                    'api_type'         =>  5, //0中台系统 1商城积分兑换订单 2商城普通订单
                    'api_order_id'     => 0, //商城订单ID
                    'case_id'=> $order['case_id'],
                    'case_order_id'=>$order->id
                ];
                $shopRefundOrderModel =new ShopRefundOrderModel();
                // 需要放开
                $shopRefundOrderRes = $shopRefundOrderModel->create($orderData);

                $orderGoodsList['order_id'] = $shopRefundOrderRes->id;
                $orderGoodsList['create_time'] = $time;
                $orderGoodsList['refund_mode'] = '01';
                $orderGoodsList['refund_mode_name'] = '现金';
                $orderGoodsList['bank_number'] = '';
                $orderGoodsList['data_business_type'] = 0;
                $orderGoodsList['data_business_two_type'] = 0;
                $orderGoodsList['data_sales_policy'] = "";  //销售政策编码
                $orderGoodsList['pay_price'] = $order->total_amount;
                $orderGoodsList['gift_price'] = 0;
                $orderGoodsList['descs'] = '病例开单收款';

                $shopRefundOrderGoodsModel = new ShopRefundOrderGoods();
                $res =  $shopRefundOrderGoodsModel->create($orderGoodsList);


                //处理顾客的预存
                $balanceData   = [
                    'change_type'  => 1,      // 变动类型 1:增加 2:减少
                    'change_balance' => $order->total_amount,
                    'change_gift_balance' => 0,
                ];
                // 新单变更数据集
                $newOrderData  = [
                    'cj_time'  => $orderData['deal_time'],// 成交时间-时间戳
                    'cj_money'    => $order->total_amount,     // 成交金额
                    'cj_order_id' => $shopRefundOrderRes->id,     // 成交的订单单号
                ];
                // 本次需要新增的订单金额
                $orderInfo     = [
                    'customer_id'=>$orderData['uid'],
                    'order_id'=>$shopRefundOrderRes->id,
                    'type'=>3,
                    'notes'=>703,
                    'remarks'=>'病例开单-拆单-收款单-传统支付'
                ];
                $customerModel->processingFunds($orderData['uid'],$balanceData,$orderData['deal_time'],$newOrderData,$orderInfo,[]);
//                //金蝶推送云星空订单
                $refundModel = new Refund();
//                $refundModel->sendYxk($orderData['uid'],3,$shopRefundOrderRes->id);
                $is_send_yxk_receipt = true;
                $receipt_id = $shopRefundOrderRes->id;
                /************************开始发短信******************/
                $consumption_amount = $orderData['total_amount']; //消费金额（本金+赠金+店转）
                $customer_id = $orderData['uid'];
                if($consumption_amount >0)
                {
                    $shop_id = $order['shop_id'];
                    $shopinfo = Db::name('shop')->where('shop_id',$shop_id)->field('shop_name,city_name,market_id')->find();
                    $customerData  = DB::name('customer')->where('id',$customer_id)->field('telephone,is_show_balance,customer_name')->find();

                    $is_send_msgtemplate = $refundModel->is_send_msgtemplate($customerData['telephone']);
                    $shopName = $shopinfo['shop_name'];

                    if(!empty($is_send_msgtemplate)){
                        //推送公众号
                        $order_no = $orderData['refund_order_no']; //订单号

                        $time = date('Y-m-d h:i:s',$time); //支付时间
                        //收款
                        $sendData = [
                            'open_id'=>$is_send_msgtemplate,
                            'data'=>[
                                'character_string4'=>['value'=>$order_no],
                                'time2'=>['value'=>$time],
                                'thing10'=>['value'=>$customerData['customer_name']],
                                'thing3'=>['value'=>$shopName],
                                'amount1'=>['value'=>$consumption_amount]
                            ]
                        ];
                        $refundModel->send_msg($orderData['type'],$sendData);


                    }else{
                        //发短信
                        $is_send = $customerData['is_show_balance'];
                        $telephone = $customerData['telephone'];
                        $residue_amount = Db::name('customer_account')->where('id', $customer_id)->value('(IFNULL(balance, 0) + IFNULL(gift, 0))'); //消费后剩余余额
                        $sendData = [
                            'market_id' => $shopinfo['market_id'],
                            'shop_id' => $shop_id,
                            'customer_id' => $customer_id,
                            'telephone' => $telephone,
                            'content' => '【欣奕除疤】尊敬的客户您好，您于'.date('y-m-d H:i',$time).'分 在'.$shopName.'服务中心消费'.$consumption_amount.'元，当前余额'.$residue_amount.'元，如有疑问，可致电400-668-8162。拒收请回复R',
                            'type' => 1,
                            'order_id' => $order->id,
                            'order_type' => $orderData['type'],
                            'expend_money' => $consumption_amount,
                            'surplus_money' => $residue_amount,
                        ];
                        //开始发短信
                        $sendMsg = new SendMsg();
                        $sendMsg->sendSMS($sendData);
                    }
                }

                /************************结束发短信******************/

            }

            $is_send_yxk_out = false;  //出库单推星空使用
            $out_id = 0;  //出库单推星空使用

            if($request['is_affirm']==1)
            {
                //遵循只开商品+冲减优惠
                $orderGoods = MedicalRecordsOrderGoods::where('order_id',$order_id)
                    ->where(function($query)use($order_id){
                        $query->where('is_project',2);
                        $query->whereOr('kingdee_code','101.12.098');
                    })->select()->toArray();

                //进行拆单动作
                //只拆出库单
                $time = time();
                $shopOrderModel = new ShopOrderModel();

                $data = [
                    'uid'                =>  $order->uid, // 客户
                    'uid_source_type_id' =>  $order['source_type_id'],
                    'uid_source_id'      =>  $order['source_id'],
                    'consignee'          => trim($order['consignee']), // 收货人
                    'order_no'           => $this->getOrderNo(), // 订单号
                    'sale_id'            => $order['sale_id'], // 销售员id
                    'sale_name'          => trim($sale['name']), // 销售员姓名
                    'shop_id'            => $order['shop_id'], // 门店id
                    'shop_name'          => trim($shop['shop_name']), // 门店名称
                    'operator_id'        => $order['operator_id'],//制单员id
                    'operator_name'      => $operator['realname'],//制单员姓名
                    'create_time'        => $time, // 创建时间
                    'deal_time'          => $order['deal_time'], // 成交日期

                    'goods_price'        => $order['goods_price'], // 订单标准金额 之和
                    'total_amount'       => $order['total_amount'], // 订单总金额 之和

                    'order_amount'       =>  $order['order_amount'], // 订单优惠后的金额
                    'pay_amount'          =>  $order['pay_amount'], // 实收本金
                    'gift_amount'         =>  $order['gift_amount'], // 实收赠金

                    'description'           => $order['description'].'-病例开单-拆出来', // 订单描述
                    'order_type'            => $order['order_type'], // 订单类型 1新单 2补单

                    'market_id'            => $shop['market_id'] , // 市场id
                    'market_name'          => $shop['market_name'], // 市场名称
                    'sales_organization'   => $order['sales_organization'], // 销售组织编码
                    'sales_name'           => $order['sales_name'], // 销售组织名称
                    'settlement_organization'       => $order['settlement_organization'], // 结算组织编码
                    'settlement_name'       => $order['settlement_name'], // 结算组织名称
                    'order_experience'       =>  $order['order_experience'],//订单是否有体验商品
                    'delivery_name'       => $order['delivery_name'], // 发货部门名称
                    'delivery_king'       => $order['delivery_king'], // 发货部门编码
                    'case_id' => $order['case_id'],
                    'case_order_id'=> $order['id'],
                    'api_type'     => 4, //0中台系统 1商城积分兑换订单 2商城普通订单  3 核销记录出库单 4 病例拆单

                ];
                $shoporder = $shopOrderModel->create($data);

                $customerModel = new \app\crm\model\Customer();
                $shopOrderGoodsModel = new ShopOrderGoods();

                $serviceDataAll = [];
                $project = [];
                if(!empty($project_ids)){
                    $project = ProductItem::whereIn('id',$project_ids)->where('status',1)->column('price,name,number,product_info,type_one,type_two,type_three','id');
                }

                $customerBalance['money'] = $benj;
                $customerBalance['complimentary_money'] = $zengj;

                $orderModel = new Order();
                $once_cancel_balance =  $once_cancel_gift = $once_discount_amount = 0;
                $last_cancel_balance =  $last_cancel_gift = $last_discount_amount = 0;

                foreach ($goods as $kk=>$pv){
                    $orderGoodsList = [];
                    $orderGoodsList['pay_amount'] = $pv['pay_amount'];
                    $orderGoodsList['gift_amount'] = $pv['gift_amount'];
                    $orderGoodsList['shop_transfer_amount'] = 0;
                    $orderGoodsList['discount_amount'] = isset($pv['discount_amount']) ? $pv['discount_amount']:0;
                    $orderGoodsList['number'] = $pv['number'];

                    $orderGoodsList['order_id'] = $shoporder->id;
                    $orderGoodsList['create_time'] = $time;
                    $orderGoodsList['goods_id'] = $pv['id'];
                    $orderGoodsList['goods_name'] = $pv['goods_name'];
                    $orderGoodsList['kingdee_code'] = $pv['kingdee_code'];
                    $orderGoodsList['goods_price'] = $pv['goods_price'];
                    $orderGoodsList['pay_price'] = $pv['pay_price'];
                    $orderGoodsList['spec_name'] = $pv['spec_name'];
                    $orderGoodsList['unit_code'] = $pv['unit_code'];
                    $orderGoodsList['unit_name'] = $pv['unit_name'];

                    $orderGoodsList['service_goods_str'] = $pv['service_goods_str'];

                    $orderGoodsList['desc'] = $pv['desc'];
                    $orderGoodsList['is_project'] = $pv['is_project'];//是否服务 1 是 2否
                    $orderGoodsList['category_id'] = $pv['category_id'];
                    $orderGoodsList['is_coupon_goods'] = 0;//是否优惠券商品 0否 1是
                    $orderGoodsList['project_type'] = $pv['project_type'];//服务类型 1 按次 2按天
                    $orderGoodsList['service_number'] = $pv['service_number'];//服务次数
                    $orderGoodsList['start_time'] = $pv['start_time']; //服务开始时间
                    $orderGoodsList['end_time'] = $pv['end_time'];  //服务结束时间
                    $orderGoodsList['is_gift'] = $pv['is_gift']  ;  //是否为赠品
                    $orderGoodsList['house_code'] = $pv['house_code'];
                    $orderGoodsList['coupon_type'] =  0;//优惠券类型
                    $orderGoodsList['house_code_name'] = $pv['house_code_name'];
                    $orderGoodsList['goods_alias_name'] =  $pv['goods_alias_name'];
                    $orderGoodsList['prestock_type'] =  $pv['prestock_type'] ; //预存货类型
                    $orderGoodsList['takeout_stock_num'] = $pv['number'];  //出货数量
                    $orderGoodsList['data_business_type'] = $pv['data_business_type'];  //业务类型
                    $orderGoodsList['data_business_two_type'] = $pv['data_business_type'];  //业务类型
                    $orderGoodsList['discount_amount'] = $pv['discount_amount'];  ////折扣金额
                    $orderGoodsList['after_discount_amount'] = $pv['after_discount_amount'] ;  //优惠后金额
                    $order_goods_res = $shopOrderGoodsModel->create($orderGoodsList);

                    if($pv['is_project'] == 1){

                        list($once_cancel_balance,$once_cancel_gift,$last_cancel_balance,$last_cancel_gift,$once_discount_amount,$last_discount_amount)
                            = $orderModel->getRealCancelAmount($orderGoodsList);

                        //品项添加-按照次卡形式
                        for($i=1;$i<=$orderGoodsList['number'];$i++){
                            $oneService = [];
                            $oneService['name']    = $orderGoodsList['goods_name'];  //服务名称
                            $oneService['goods_alias_name']  = $orderGoodsList['goods_alias_name'];  //服务名称
                            $oneService['shop_id'] =  $data['shop_id'];    // 店铺id
                            $oneService['customer_id']  = $data['uid'];   // 必填--客户id
                            $oneService['order_id']  = $shoporder->id;
                            $oneService['order_goods_id']  = $order_goods_res->id;
                            $oneService['service_type'] = 2;   // 必填--服务类型：1按期2按次
                            $oneService['num'] = isset($project[$pv['goods_id']])?$project[$pv['goods_id']]['number']:0;   // 次卡可服务次数

                            $oneService['start_time']   = 0;    // 类型为1 是必填--服务开始时间
                            $oneService['end_time']     = 0;      // 类型为1 是必填--服务开始时间
                            $oneService['experience']   = 0;     // 0否1是 是否体验
                            $oneService['kk_user_id']   = $data['sale_id'];  // 开卡人id
                            $oneService['goods_id']     = $orderGoodsList['goods_id'];
                            $kk_money = bcmul($pv['pay_price'],1,2);
                            if($kk_money>0){
                                $customerBalance['actual_order_amout'] = $kk_money;
                                $balance_consumed = $customerModel->getCustomerAmountConsumed($customerBalance);
                                $oneService['consume_store_transfer'] = 0;
                                $oneService['consume_gratuity'] =  $balance_consumed['pay_zengjin_amount'];
                                $oneService['consume_money'] =  $balance_consumed['pay_benjin_amount'];
                            }


                            if(isset($project[$pv['goods_id']])){
                                if($i == 1){
                                    $oneService['real_cancel_balance'] = $once_cancel_balance;
                                    $oneService['real_cancel_gift'] = $once_cancel_gift;
                                    $oneService['discount_amount'] = $once_discount_amount;
                                }
                                else{
                                    if($i<$orderGoodsList['number'] ){
                                        $oneService['real_cancel_balance'] = $once_cancel_balance;
                                        $oneService['real_cancel_gift'] =  $once_cancel_gift;
                                        $oneService['discount_amount'] = $once_discount_amount;
                                    }
                                    elseif($i==$orderGoodsList['number'] ){
                                        $oneService['real_cancel_balance'] = $last_cancel_balance;
                                        $oneService['real_cancel_gift'] =  $last_cancel_gift;
                                        $oneService['discount_amount'] = $last_discount_amount;
                                    }
                                }
                            }

                            $oneService['service_max_num'] = $oneService['num']; //最高进店次数
                            $oneService['kk_money']     = $kk_money;       // 开卡金额
                            $oneService['category_type_one']  = isset($project[$pv['goods_id']])?$project[$pv['goods_id']]['type_one']:0;       // 品项的一级分类
                            $oneService['category_type_two']  = isset($project[$pv['goods_id']])?$project[$pv['goods_id']]['type_two']:0;       // 开卡金额
                            $oneService['category_type_three']  = isset($project[$pv['goods_id']])?$project[$pv['goods_id']]['type_three']:0;       // 开卡金额

                            array_push($serviceDataAll,$oneService);
                        }
                    }
                }

                $addServiceRes = $customerModel->addCustomService($data['uid'],$serviceDataAll);
                if(!$addServiceRes){
                    throw new \Exception("服务创建失败");
                }

                //处理顾客的预存-
                $balanceData   = [
                    'change_type'  => 2,      // 变动类型 1:增加 2:减少
                    'change_balance' => $order['pay_amount'],
                    'change_gift_balance' => $order['gift_amount'],
                ];
                // 新单变更数据集
                $newOrderData  = [  ];
                // 本次需要新增的订单金额
                $orderInfo     = [
                    'customer_id'=>$data['uid'],
                    'order_id'=>$shoporder->id,
                    'type'=>4,
                    'notes'=>707,
                    'remarks'=>'出货单'
                ];

                $customerModel->processingFunds($data['uid'],$balanceData,$data['deal_time'],$newOrderData,$orderInfo,[]);

                //出库单推送云星空
                if(in_array(1,$is_send_yxk)){
                    $is_send_yxk_out = true;
                    $out_id = $shoporder->id;
//                    //金蝶推送云星空订单
//                    $refundModel = new Refund();
//                    $refundModel->sendYxk($data['uid'],6,$shoporder->id);
                }
                else{
                    ShopOrderModel::where('id',$shoporder->id)->update(['status'=>2]);
                }

                $order->status = 3;
                //调整病例-成交状态
                $case = MedicalRecords::where('id',$order->case_id)->find();

                if(!empty($case)){
                    if($case->is_bargain == 1){
                        $case->bargain_money = bcadd($case->bargain_money,$order->total_amount,2);
                    }else{
                        $case->is_bargain = 1;
                        $case->bargain_money = $order->total_amount;
                        $case->bargain_time = time();
                    }
                    $case->update_time = time();
                    $case->save();
                }


                /************************开始发短信******************/
                $consumption_amount = $data['total_amount']; //消费金额（本金+赠金+店转）
                $customer_id = $data['uid'];
                if($consumption_amount >0) {
                    $refundModel = new Refund();
                    $shop_id = $order['shop_id'];
                    $shopinfo = Db::name('shop')->where('shop_id',$shop_id)->field('shop_name,city_name,market_id')->find();
                    $customerData  = DB::name('customer')->where('id',$customer_id)->field('telephone,is_show_balance,customer_name')->find();

                    $is_send_msgtemplate = $refundModel->is_send_msgtemplate($customerData['telephone']);
                    $shopName = $shopinfo['shop_name'];

                    if(!empty($is_send_msgtemplate)){
                        //推送公众号
                        $order_no = $data['order_no']; //订单号

                        $time = date('Y-m-d h:i:s',$time); //支付时间
                        //收款
                        $sendData = [
                            'open_id'=>$is_send_msgtemplate,
                            'data'=>[
                                'character_string4'=>['value'=>$order_no],
                                'time2'=>['value'=>$time],
                                'thing10'=>['value'=>$customerData['customer_name']],
                                'thing3'=>['value'=>$shopName],
                                'amount1'=>['value'=>$consumption_amount]
                            ]
                        ];
                        $refundModel->send_msg(4,$sendData);
                    }else{
                        //发短信
                        $is_send = $customerData['is_show_balance'];
                        $telephone = $customerData['telephone'];
                        $residue_amount = Db::name('customer_account')->where('id', $customer_id)->value('(IFNULL(balance, 0) + IFNULL(gift, 0))'); //消费后剩余余额
                        $sendData = [
                            'market_id' => $shopinfo['market_id'],
                            'shop_id' => $shop_id,
                            'customer_id' => $customer_id,
                            'telephone' => $telephone,
                            'content' => '【欣奕除疤】尊敬的客户您好，您于'.date('y-m-d H:i',$time).'分 在'.$shopName.'服务中心消费-'.$consumption_amount.'元，当前余额'.$residue_amount.'元，如有疑问，可致电400-668-8162。拒收请回复R',
                            'type' => 1,
                            'order_id' => $order->id,
                            'order_type' => 4,
                            'expend_money' => $consumption_amount,
                            'surplus_money' => $residue_amount,
                        ];
                        //开始发短信
                        $sendMsg = new SendMsg();
                        $sendMsg->sendSMS($sendData);
                    }
                }
                /************************结束发短信******************/
            }

            $res = $order->save();
            if(!$res){
                throw new \Exception('订单修改失败，请稍后重试');
            }

            if($is_send_yxk_receipt){
                //推送星空
                $refundModel = new Refund();
                $refundModel->sendYxk($order['uid'],3,$receipt_id);
            }
            if($is_send_yxk_out){
                //推送星空
                $refundModel = new Refund();
                $refundModel->sendYxk($order['uid'],6,$out_id);
            }
            Db::commit();

            $this->error = '订单修改成功';
            return true;

        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return [];
        }
    }

    //获取顾客剩余接口
    public function getCustomerAccount($request){

        try {
            $customer_id = $request['customer_id'] ??0;
            if(empty($customer_id)){
                throw new \Exception('顾客id不合法');
            }
            $account = CustomerAccount::where('id',$customer_id)->find();
            $account = empty($account)?[]:$account->toArray();
            return $account;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }
    }


    /**
     * 订单主要详情
     * @param array $request
     * @return array
     * @author SL
     * @create 2021-06-02
     */

    public function getOrderDetail($request)
    {
        try {

            $id = $request['order_id'] ?? 0;
            if(!$id){
                throw new \Exception('请传入订单id');
            }
            $detail = $this->where('id',$id)->find();
            if($detail){
                $detail = $detail->toArray();
                $status = [
                    0=>'待支付', 1=>'已支付', 2=>'待拆单', 3=>'已下推', 4=>'已作废'
                ];

                $refund_type_plus = [
                    1=>'通联支付', 2=>'现付方式', 3=>'通联远程', 4=>'余额支付', 5=>'组合支付'
                ];

                $pay_mode = [
                    1=>'通联支付', 2=>'现付方式', 3=>'通联远程',
                ];

                $type_store = [
                    1=>'初诊', 2=>'复诊', 3=>'再消费', 4=>'诊疗', 5=>'其他'
                ];

                $detail['refund_type_plus_text'] = $refund_type_plus[$detail['refund_type_plus']]??'';
                $detail['pay_mode_text'] = $pay_mode[$detail['pay_mode']]??'';

                $detail['status_text'] = $status[$detail['status']]??'';
                $detail['pay_time'] = $detail['pay_time'] ? date('Y-m-d H:i:s', $detail['pay_time']) : '';
                $detail['cancel_time'] = $detail['cancel_time'] ? date('Y-m-d H:i:s', $detail['cancel_time']) : '';
                $detail['order_type']    = $type_store[$detail['order_type']] ??'';
                $detail['deal_time'] = $detail['deal_time'] ? date('Y-m-d', $detail['deal_time']) : '';
                $detail['shop_name'] = ShopModel::where('shop_id',$detail['shop_id'])->value('shop_name');
                $detail['sale_name'] = ShopPerson::where('id',$detail['sale_id'])->value('name');

                $caseOrderGoodsModel = new MedicalRecordsOrderGoods();
                $detail['goods']  = $caseOrderGoodsModel->where('order_id',$id)->select()->toArray();

                foreach($detail['goods'] as $k=>&$v){
                    $v['order_goods_price'] = bcmul($v['pay_price'],$v['number'],2);
                    $v['project_type_text'] = $v['is_project'] == 1?'品项':'商品';
                    $v['prestock_type'] =  $v['prestock_type'] == 1?'不存货':'';
                    $v['project_time_num'] = '';
                    if($v['project_type'] == 1){
                        $v['project_time_num'] = $v['project_type'] == 1 ?$v['service_number'].'次':date('Y-m-d',$v['start_time']).'至'.date('Y-m-d',$v['edn_time']);
                    }

                    $service_goods_str = !empty($v['service_goods_str'])?json_decode($v['service_goods_str'],1):[];
                    $serviceGodosArr = [];
                    foreach ($service_goods_str as &$item) {
                        $serviceGodos = [
                            'goods_name'=>$item['name'],
                            'goods_alias_name' =>'--',
                            'is_project_text'=>'--',
                            'goods_price'=>$item['goods_price'],
                            'pay_price'=>$item['package_price'],
                            'number'=>$item['number'],
                            'order_goods_price'=>'--',
                            'project_time_num'=>'--',
                            'prestock_type'=>'---'
                        ];
                        array_push($serviceGodosArr,$serviceGodos);
                    }
                    $v['children'] = $serviceGodosArr;
                }
            }
            else{
                throw new \Exception('订单不存在');
            }
            $userId  = $request['user_id'] ?? 0;
            $permission = get_user_permission_menu($userId,'order_list_tag');
            $detail['menu_list'] = $permission ? $permission : [];
            return $detail;

        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }

    }




    /**
     * 订单商品详情
     * @param array $request
     * @return array
     * @author SL
     * @create 2021-06-02
     */
    public function getGoodsDataDetail($request)
    {

        try {
            $id = $request['order_id'] ?? 0;
            if(!$id){
                throw new \Exception('请传入订单id');
            }

            $detail = ShopOrderModel::find($id);
            if(empty($detail)) {
                throw new \Exception('订单不存在');
            }
            // 订单商品

            $list = ShopOrderGoods::where('order_id', $id)
                ->field('id,goods_alias_name,takeout_stock_num,number,pay_price,goods_price,goods_name,project_type,is_project,service_goods_str,project_type,prestock_type,service_number,start_time,end_time')
                ->order('id','desc')
                ->select()->toArray();

            $prestock_type = [
                1=>'不存货', 2=>'存货', 3=>'出货',
            ];
            $is_project = [
                0=>"----",1=>'品项', 2=>'商品',
            ];
            $service_type  = [
                0=>"----",1=>'按次',2=>"疗程"
            ];

            foreach ($list as $key => &$val) {
                $val['project_type_text'] = $service_type[$val['project_type']]??'';
                $val['is_project_text'] = $is_project[$val['is_project']]??'';
                $val['order_goods_price'] = bcmul($val['pay_price'],$val['number'],2);
                $val['prestock_type'] = $prestock_type[$val['prestock_type']]??'';

                $val['project_time_num']  = '----';
                if($val['is_project'] == 1 && $val['project_type'] == 1){
                    $val['project_time_num'] = $val['service_number'].'次';
                } elseif($val['is_project'] == 1 && $val['project_type'] == 2){
                    $val['project_time_num'] = date('Y-m-d h:i',$val['start_time']).'-'.date('Y-m-d h:i',$val['end_time']);
                }
                $val['children'] = [];
                if(!empty($val['service_goods_str'])){
                    $children = json_decode($val['service_goods_str'],1);
                    $childrens = [];
                    foreach ($children as $k=>$v){
                        $child=[];
                        $child['id'] =$v['id'];
                        $child['goods_name'] =$v['name'];
                        $child['goods_alias_name'] = '----';
                        $child['is_project_text'] = '商品';
                        $child['goods_price'] =$v['goods_price'];
                        $child['pay_price'] = '----';
                        $child['number'] = $v['number'];
                        $child['order_goods_price'] = '----';
                        $child['project_type_text'] = '----';
                        $child['project_time_num'] = '----';
                        $child['prestock_type'] = '----';
                        $child['takeout_stock_num'] = '----';
                        $child['service_goods_str'] = '----';
                        $child['start_time'] = '----';
                        $child['end_time'] = '----';
                        $child['project_type'] = '----';
                        $child['is_project'] = '----';
                        $child['service_number'] = '----';

                        array_push($childrens,$child);
                    }
                    $val['children'] = $childrens;
                }
            }
            return $list;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }

    }

    /**
     * 订单商品详情
     * @param array $request
     * @return array
     * @author SL
     * @create 2021-06-02
     */

    public function orderGoodsOptionDetail($request){

        try {

            $id = $request['order_id'] ?? 0;
            if(!$id){
                $this->error = '请传入订单id';
                return [];
            }

            $list =[];
            $detail = Db::name('shop_order')->field('id')->where('id',$id)->find();

            if($detail)
            {
                $list = ShopOrderGoodsOptionLog::with(['NurseOne'=>function($query){
                    $query->field('name,id');
                },'NurseTwo'=>function($query){
                    $query->field('name,id');
                },'shopGoods'=>function($query){
                    $query->field('id,goods_name');
                }]) ->field('id,nurse_one,nurse_two,nurse_one_project,nurse_two_project,create_time,shop_order_goods_id,is_new')
                    ->where('order_id', $id)
                    ->order('id DESC')
                    ->select()->toArray();

                foreach ($list as $key => &$value)
                {
                    $value['nurse_one_name'] = !empty($value['NurseOne'])?$value['NurseOne']['name']:'';
                    $value['nurse_one'] = !empty($value['NurseOne'])?$value['NurseOne']['id']:'';
                    $value['nurse_two_name'] = !empty($value['NurseTwo'])?$value['NurseTwo']['name']:'';
                    $value['nurse_two'] = !empty($value['NurseTwo'])?$value['NurseTwo']['id']:'';
                    $value['goods_name'] = !empty($value['shopGoods'])?$value['shopGoods']['goods_name']:'';
                    $value['nurse_one_project_text'] = $value['nurse_two_project_text'] = '';

                    if(!empty($value['nurse_one_project'])){
                        $one_project = explode(',',$value['nurse_one_project']);
                        $project_data = Db::name('shop_person_controls')->whereIn('id',$one_project)->field('id as value,name as lable')->select()->toArray();
                        $value['nurse_one_project'] = array_column($project_data,'value');
                        $value['nurse_one_project_text'] = implode(',',array_column($project_data,'lable'));
                    }
                    if(!empty($value['nurse_two_project'])){
                        $two_project = explode(',',$value['nurse_two_project']);
                        $project_data = Db::name('shop_person_controls')->whereIn('id',$two_project)->field('id as value,name as lable')->select()->toArray();
                        $value['nurse_two_project'] = array_column($project_data,'value');
                        $value['nurse_two_project_text'] = implode(',',array_column($project_data,'lable'));
                    }
                }
            } else{
                $this->error = '订单不存在';
                return false;
            }

            $detail['list'] = $list;

            return $detail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];
        }

    }




    /**

     * 订单验证公共方法
     * @param  array $data 请求参数
     * @return bool
     * @author SL
     * @create 2021-06-03
     */

    function orderAdd($data){
        $result=['status'=>1,'error'=>''];

        if (isset($data['is_outreach'])) {
            if (!isset($data['outreahc_id'])) {
                $result['error']='外联选是时，外联人必须选择';
                $result['status']=0;
                return $result;
            }
        }

        if (isset($data['is_introduction'])) {
            if (!isset($data['introduction_id'])) {
                $result['error']='转介绍选是时，转介绍人必须选择';
                $result['status']=0;
                return $result;
            }
        }
        return $result;
    }



    //交过会费，然后调整账户
    public function sendCoupon($sendCoupon){
        $consumptionAll = $sendCoupon['consumptionAll'];
        // 入会即时发券 --------start---------
        $card_id = ['175','176','177','178','179','180','181','182','183','184'];
        $isSend = CouponProvideCustomer::where('customer_id',$sendCoupon['customer_id'])
            ->whereIn('coupon_id',$card_id)
            ->select()->toArray();
        $coupon = Coupon::whereIn('id',$card_id)->cache(3600)->column('start_time,end_time','id');
        if(empty($isSend)){
            $time = time();
            $cardList = array();
            if(floor($consumptionAll)>='5000' && floor($consumptionAll)<'15000'){
                array_push($cardList,'175','176');
            }elseif  (floor($consumptionAll)>='15000' && floor($consumptionAll)<'50000'){
                array_push($cardList,'177','178','179','180');
            }elseif (floor($consumptionAll)>='50000'){
                array_push($cardList,'181','182','183','184');
            }

            $provideCustomerList = array();
            foreach ($cardList as $k1 => $v1) {
                $provideCustomer = [];
                $provideCustomer['coupon_id'] = $v1;
                $provideCustomer['start_time'] = isset($coupon[$v1])?$coupon[$v1]['start_time']:0;
                $provideCustomer['end_time'] = isset($coupon[$v1])?$coupon[$v1]['end_time']:0;
                $provideCustomer['create_time'] = $time;
                $provideCustomer['customer_id'] = $sendCoupon['customer_id'];
                array_push($provideCustomerList,$provideCustomer);
            }
            CouponProvideCustomer::saveAll($provideCustomerList);
        }
        return true;
    }


    public function getMaxCustomerEnterShop($start_time,$end_time,$half_num,$month_max){
        $begin_year = date('Y',$start_time);
        $end_year = date('Y',$end_time);
        $year_diff = $end_year - $begin_year;
        $begin_month = date('m',$start_time);
        $end_month = date('m',$end_time);
        $month_diff = $end_month - $begin_month;

        $shou_yue_max_service_num = 0;
        $zhong_yue_max_service_num = 0;
        $end_yue_max_servcie_num = 0;

        if($month_diff == 0 && $begin_year == $end_year){ //同年同月份

            if($end_time -  $start_time <=(60*60*24*15)){
                $service_max_num = $half_num;
            }else{
                $service_max_num = $month_max;
            }
            $shou_yue_max_service_num = $service_max_num;
        }else if($month_diff == 1 && $begin_year == $end_year){ //同年相邻月份
            $begin_end_month_day = strtotime(date('Y-m-t',$start_time).'23:59:59');
            if($begin_end_month_day -  $start_time <=(60*60*24*15)){
                $begin_max_num = $half_num;
            }else{
                $begin_max_num = $month_max;
            }
            $shou_yue_max_service_num = $begin_max_num;
            $end_day = date('d',$end_time);
            if($end_day == 1){
                $end_max_num = 0;
            }else if(1<$end_day && $end_day<=15){
                $end_max_num = $half_num;
            }else{
                $end_max_num = $month_max;
            }
            $end_yue_max_servcie_num = $end_max_num;
            $service_max_num = $begin_max_num + $end_max_num;
        }else{

            if($begin_year == $end_year){

                $begin_end_month_day = strtotime(date('Y-m-t',$start_time).'23:59:59');
                if($begin_end_month_day - $start_time <=(60*60*24*15)){
                    $begin_max_num = $half_num;
                }else{
                    $begin_max_num = $month_max;
                }

                $shou_yue_max_service_num = $begin_max_num;
                $end_day = date('d',$end_time);
                if($end_day == 1){
                    $end_max_num = 0;
                }else if(1<$end_day && $end_day<=15){
                    $end_max_num = $half_num;
                }else{
                    $end_max_num = $month_max;
                }
                $end_yue_max_servcie_num = $end_max_num;
                $zhong_yue_max_service_num = $month_max;
                $service_max_num = $begin_max_num + $end_max_num +  (($month_diff-1) *$month_max);
            }else{

                //跨年年份
                $begin_diff = 12-$begin_month;
                $begin_max_num = 0;
                $begin_end_month_day = strtotime(date('Y-m-t',$start_time).'23:59:59');
                if($begin_end_month_day - $start_time <=(60*60*24*15)){
                    $begin_max_num = $half_num;
                }else{
                    $begin_max_num = $month_max;
                }
                $shou_yue_max_service_num = $begin_max_num;

                if($begin_diff>0){
                    $begin_max_num = $begin_max_num+($begin_diff*$month_max);
                    $zhong_yue_max_service_num = $month_max;
                }

                $end_diff = $end_month -1;

                $end_day = date('d',$end_time);

                if($end_day == 1){
                    $end_max_num = 0;
                }else if(1<=$end_day && $end_day<=15){
                    $end_max_num = $half_num;
                }else{
                    $end_max_num = $month_max;
                }
                $end_yue_max_servcie_num = $end_max_num;

                if($end_diff>0){
                    $end_max_num = $end_max_num+($end_diff*$month_max);
                    $zhong_yue_max_service_num = $month_max;
                }

                $service_max_num = $begin_max_num+$end_max_num;
                if($year_diff >1){
                    $service_max_num  = $service_max_num + (12*$month_max);
                    $zhong_yue_max_service_num = $month_max;
                }
            }

        }
        return ['service_max_num'=>$service_max_num,'shou'=>$shou_yue_max_service_num,'zhong'=>$zhong_yue_max_service_num,'wei'=>$end_yue_max_servcie_num];
    }


    /**
     * 生成订单号
     * @param  array $request 请求参数
     * @return String
     * @author SL
     * @create 2021-06-03
     */
    public function getOrderNo()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while(true){
            $order_sn = date('YmdHis').rand(1000,9999); // 订单编号
            $order_sn_count = DB::name('shop_order')->where('order_no', $order_sn)->count();
            if($order_sn_count == 0)
                break;
        }
        return $order_sn;
    }

    /**
     * 订单操作记录
     * @param  array $request 请求参数
     * @return array
     * @author SL
     * @create 2021-06-10 9:33
     */
    public function getOrderRecordList(array $request): array
    {
        $orderId = $request['order_id'] ?? 0;
        if (!$orderId) {
            $this->error = '参数错误';
            return [];
        }
        $page  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $limit = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
        return $this->getActionRecordListByPage($orderId, 'shop', 'order', 0, $page, $limit);
    }


    /**
     * 获取订单列表
     * @param  array $request 请求参数
     * @return array
     * @author SL
     * @create 2021-06-1
     */

    public function lcokOrderData($request)
    {

        try {

            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $request = $this->fmtRequest($request);

            $map     = $request['map'] ?? [];

            $where   = [];

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            $noValue      = isset($map['no_value']) && $map['no_value'] ? trim($map['no_value']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            // 获取客户数据权限 的客户名称

            if ($shopIds) {
                array_push($where, ['shop_id', 'in', $shopIds]);
            }

            if ($uid) {
                //会员id搜索
                array_push($where, ['uid', '=', $uid]);
            }

            if ($shop_id) {
                //门店id搜索
                array_push($where, ['shop_id', '=', $shop_id]);
            }

            if ($shop_name) {
                //门店名称搜索
                array_push($where, ['shop_name', 'like', '%'.$shop_name.'%']);
            }
            if ($consignee) {
                // 客户名称搜索
                array_push($where, ['consignee', 'like', '%'.$consignee.'%']);
            }

            if ($noValue) {
                array_push($where, ['order_no', '=', $noValue]);
            }

            // 时间
            if($start_time && $end_time)
            {
                array_push($where, ['deal_time', 'between', "$start_time,$end_time"]);
            }

            if ($business_type) {
                //业务类型搜索
                array_push($where, ['business_type', '=', $business_type]);
            }

            if ($order_type) {
                //订单类型搜索
                array_push($where, ['order_type', '=', $order_type]);
            }

            if ($low_total && !$large_total) {
                array_push($where, ['order_amount', 'egt', $low_total]);
            }

            if (!$low_total && $large_total) {
                array_push($where, ['order_amount', 'elt', $large_total]);
            }

            if ($low_total && $large_total) {
                array_push($where, ['order_amount', 'between', "$low_total,$large_total"]);
            }
            $sqlQuery = $this->where($where);
            $dataCount  = $sqlQuery->count();
            $bool=0;

            if ($dataCount) {
                $bool = $sqlQuery->update(['is_lock' => 1]);
            }
            $this->error = '锁定成功'.$bool.'单';
            $data              = [];
            $data['dataCount'] = $bool ?? 0;
            return $data;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }
    }









}

